package com.gzhryc.net_marketing.cloud.business;

import com.gzhryc.common.IDTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.shared_device.common.payment.services.WXPayOrderService;
import com.gzhryc.shared_device.common.payment.services.WXRefundOrderService;
import com.gzhryc.shared_device.common.payment.services.dto.WXPayOrderSearch;
import com.gzhryc.shared_device.oem.code.BaseConstants;
import com.gzhryc.shared_device.oem.code.order.OrderTradeNoPrefix;

import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 订单号工具
 */
public class TradeNoUtils {

    private final static AtomicInteger counter = new AtomicInteger(1);

    public static String createTradeNo() {
        String tradeNo = OrderTradeNoPrefix.MARKET_GOODS_ORDER + IDTools.getTimestampSecondID() + String.format("%03d", counter.getAndIncrement());
        return tradeNo;
    }

    public static String createPayTradeNo(String tradeNo,Date date) throws LogicException {
    	WXPayOrderSearch search = new WXPayOrderSearch();
    	search.setBusinessTradeNo(tradeNo);
    	Long total = WXPayOrderService.self(BaseConstants.JDBC_KEY, date).countBySearch(search);
    	if(total == null) {
    		total = 1L;
    	}else {
    		total = total + 1;
    	}
    	if(total > 9) {
    		throw new LogicException("支付订单数超界");
    	}
        return tradeNo + String.format("%d", total.intValue());
    }

    public static String createRefundTradeNo(String payTradeNo,Date date) throws LogicException {
    	Long total = WXRefundOrderService.self(BaseConstants.JDBC_KEY, date).countByPayTradeNo(payTradeNo);
    	if(total == null) {
    		total = 1L;
    	}else {
    		total = total + 1;
    	}
    	if(total > 9) {
    		throw new LogicException("退款订单数超界");
    	}
        return payTradeNo + String.format("%d", total.intValue());
    }
}
